/*
 * @Author: wuqingchun
 * @Date: 2024-01-09 13:39:35
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-01-10 19:49:19
 */

#include <stdio.h>

#include "ftpc.h"
#include "ftpc_log.h"
#include "ftpc_event.h"

void FTPC_event_Init(void)
{
    int i;
    FTPC_EVENT_S* pstEvent;

    pstEvent = &g_stFTPCClient.stEvent;
    pstEvent->uiCount = 0;
    for (i = 0; i < FTPC_EVENT_FD_MAX; i++)
    {
        pstEvent->astData[i].iFd = -1;
        pstEvent->astData[i].uiEvents = 0;
    }
}

int FTPC_event_AddFd(int iFd, unsigned int uiEvents)
{
    int iErr = -1;
    int iPos;
    int iInsertPos;
    int iFlag;
    unsigned int uiCount;
    FTPC_EVENT_S* pstEvent;
    FTPC_EVENT_DATA_S* pstItem;
    
    if (iFd == -1)
    {
        return iErr;
    }

    pstEvent = &g_stFTPCClient.stEvent;
    uiCount = pstEvent->uiCount;
    iInsertPos = 0;
    iFlag = 0;
    for (iPos = 0; uiCount > 0 && iPos < FTPC_EVENT_FD_MAX; iPos++)
    {
        pstItem = pstEvent->astData + iPos;
        
        if (pstItem->iFd == -1)
        {  
            if (!iFlag)
            {
                iFlag = 1;
                iInsertPos = iPos;
            }
            
            continue;
        }

        uiCount--;
        if (pstItem->iFd == iFd)
        {
            iErr = 0;
            pstItem->uiEvents |= uiEvents;
            iInsertPos = -1;
            break;
        }

        if (!iFlag)
        {
           iInsertPos = iPos + 1; 
        }
    }

    if (iInsertPos != -1 && iInsertPos < FTPC_EVENT_FD_MAX)
    {
        pstItem = pstEvent->astData + iInsertPos;
        pstItem->iFd = iFd;
        pstItem->uiEvents = uiEvents;
        pstEvent->uiCount++;
        iErr = 0;
    }

    FTPC_LOG_DEBUG("fd=%d, count=%d", iFd, pstEvent->uiCount);

    return iErr;
}

void FTPC_event_DeleteFd(int iFd)
{
    int iErr = -1;
    FTPC_EVENT_S* pstEvent = &g_stFTPCClient.stEvent;
    FTPC_EVENT_DATA_S* pstItem;
    
    if (iFd == -1 || pstEvent->uiCount == 0)
    {
        return;
    }

    for (int i = 0; i < FTPC_EVENT_FD_MAX; i++)
    {
        pstItem = pstEvent->astData + i;
        if (pstItem->iFd == iFd)
        {
            pstItem->iFd = -1;
            pstItem->uiEvents = 0;
            pstEvent->uiCount--;
            break;
        }
    }

    FTPC_LOG_DEBUG("fd=%d, count=%d", iFd, pstEvent->uiCount);
}